package com.qingfeng.medical.controller.admin.infomation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qingfeng.medical.base.controller.BaseController;
import com.qingfeng.medical.base.log.annotation.Log;
import com.qingfeng.medical.base.log.enums.BusinessType;
import com.qingfeng.medical.base.result.Result;
import com.qingfeng.medical.base.ro.EnumsRo;
import com.qingfeng.medical.biz.information.domain.dto.DictSaveDTO;
import com.qingfeng.medical.biz.information.domain.dto.DictUpdateDTO;
import com.qingfeng.medical.biz.information.domain.entity.Dict;
import com.qingfeng.medical.biz.information.domain.vo.DictVo;
import com.qingfeng.medical.biz.information.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 数据字典表
 *
 * @author 清风学Java
 * @date 2023-04-08 23:43:31
 */
@Api(tags = "数据字典表管理")
@RestController
@RequestMapping("/admin/info/dict")
@Validated
public class DictController extends BaseController {

    @Autowired
    private DictService dictService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PreAuthorize("hasAuthority('bnt.dict.list')")
    @ApiOperation(value = "数据字典列表", notes = "数据字典列表")
    @GetMapping("/list")
    @Log(title = "数据字典管理", businessType = BusinessType.SELECT, message = "数据字典列表")
    public Result<List<DictVo>> list() {
        List<DictVo> dictVoList = dictService.findListTree();
        return Result.ok(dictVoList);
    }

    @PreAuthorize("hasAuthority('bnt.dict.list')")
    @ApiOperation(value = "根据Id查询数据字典信息", notes = "根据Id查询数据字典信息")
    @GetMapping("/info/{dictId}")
    @Log(title = "数据字典管理", businessType = BusinessType.SELECT, message = "根据Id查询数据字典信息")
    public Result<Dict> info(@ApiParam(value = "学分认定模块Id", required = true)
                             @PathVariable("dictId") @NotNull Long dictId) {
        Dict dict = dictService.getById(dictId);
        return Result.ok(dict);
    }

    @PreAuthorize("hasAuthority('bnt.dict.add')")
    @ApiOperation(value = "保存数据字典表信息", notes = "保存数据字典表信息")
    @PostMapping("/save")
    @Log(title = "数据字典表", businessType = BusinessType.INSERT, message = "保存数据字典表信息")
    public Result save(@ApiParam(value = "数据字典保存实体", required = true)
                       @RequestBody @Validated DictSaveDTO dictSaveDTO) {
        dictService.saveDict(dictSaveDTO);
        return Result.ok();
    }

    @PreAuthorize("hasAuthority('bnt.dict.update')")
    @ApiOperation(value = "修改数据字典表信息", notes = "修改数据字典表信息")
    @PutMapping("/update")
    @Log(title = "数据字典表", businessType = BusinessType.UPDATE, message = "修改数据字典表信息")
    public Result update(@ApiParam(value = "数据字典实体")
                         @RequestBody @Validated DictUpdateDTO dictUpdateDTO) {
        dictService.updateDictById(dictUpdateDTO);
        return Result.ok();
    }

    @PreAuthorize("hasAuthority('bnt.dict.delete')")
    @ApiOperation(value = "根据Ids删除数据字典表信息", notes = "根据Ids删除数据字典表信息")
    @DeleteMapping("/delete")
    @Log(title = "数据字典表", businessType = BusinessType.DELETE, message = "根据Ids删除数据字典表信息")
    public Result delete(@ApiParam(value = "学分认定模块Id", required = true)
                         @RequestBody List<Long> ids) {
        dictService.removeByIds(ids);
        // 清除redis缓存
        stringRedisTemplate.delete("dict");
        return Result.ok();
    }

    @ApiOperation(value = "导出数据字典模板", notes = "导出数据字典模板")
    @GetMapping("/excel/export_template")
    @Log(title = "数据字典表", businessType = BusinessType.EXPORT, message = "导出数据字典模板")
    public void exportTemplate(HttpServletResponse response) {
        dictService.exportTemplate(response);
    }

    @ApiOperation(value = "导出数据字典", notes = "导出数据字典")
    @GetMapping("/excel/export_dict")
    @Log(title = "数据字典表", businessType = BusinessType.EXPORT, message = "导出数据字典")
    public void exportDict(HttpServletResponse response) {
        dictService.exportDict(response);
    }

    @ApiOperation(value = "数据字典Excel导入", notes = "数据字典Excel导入")
    @PostMapping("/excel/import_dict")
    @Log(title = "数据字典表", businessType = BusinessType.IMPORT, message = "数据字典Excel导入")
    public Result userImport(MultipartFile file) {
        dictService.importDict(file);
        return Result.ok();
    }

    @ApiOperation(value = "查询证件类型", notes = "查询证件类型")
    @GetMapping("/anno/certificates")
    @Log(title = "数据字典管理", businessType = BusinessType.SELECT, message = "查询证件类型")
    public Result<List<EnumsRo>> certificatesType() {
        Dict dict = dictService.getOne(
                new LambdaQueryWrapper<Dict>()
                        .eq(Dict::getDictCode, "CERTIFICATESTYPE")
        );
        return Result.ok(
                dictService.list(
                                new LambdaQueryWrapper<Dict>()
                                        .eq(Dict::getParentId, dict.getId())
                        ).stream()
                        .map(d -> EnumsRo.builder()
                                .label(d.getDictName())
                                .value(d.getDictName())
                                .build()
                        )
                        .collect(Collectors.toList())
        );
    }
}
